<template>
  <div class="map-container">
    <div class="map-header"></div>
    <div id="map-container" ref="mapContainer"></div>
  </div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount,computed } from 'vue';
import AMapLoader from '@amap/amap-jsapi-loader';

// 地图实例
const map = ref(null);
const mapContainer = ref(null);
const marker = ref(null);
const point = ref([]);
const props = defineProps({
  data: {
    type: Object,
    default: () => ({
      defaultAddress: '',
      defaultPoint: [],
    }),
  },
});

// 计算属性获取点坐标
const defaultPoint = computed(
  () => props.data?.defaultPoint || [116.397428, 39.90923],
);
const defaultAddress = computed(() => props.data?.defaultAddress || '');

// 初始化地图
const initMap = async () => {
  try {
    const AMap = await AMapLoader.load({
      key: '4382d57ce20d54c12e3c78ae23f76876',
      version: '2.0',
      plugins: [
        'AMap.Geocoder',
        'AMap.ToolBar',
        'AMap.Scale',
        'AMap.Marker',
        'AMap.Geolocation',
      ],
    });
    point.value = defaultPoint.value;
    const center = defaultPoint.value?.[0]
      ? defaultPoint.value
      : [116.397428, 39.90923];
    // 创建地图实例
    map.value = new AMap.Map(mapContainer.value, {
      zoom: 13,
      center, // 默认北京中心点
      viewMode: '3D',
      layers: [new AMap.TileLayer.Satellite()],
    });

    // 添加定位控件
    const geolocation = new AMap.Geolocation({
      enableHighAccuracy: true,
      timeout: 10000,
      buttonPosition: 'RB',
    });
    map.value.addControl(geolocation);
    addMarker();
  } catch (error) {
    console.error('地图初始化失败:', error);
  }
};

// 增加点标记
const addMarker = () => {
var content = '<div class=""><img src="../../../../assets/add.png" alt="" /></div>';
  // 清除其他icon
  if (marker.value) {
    marker.value.setMap(null);
    marker.value = null;
  }
  // 重新渲染icon
  marker.value = new AMap.Marker({
    position: point.value, // icon经纬度
    offset: new AMap.Pixel(-13, -30), // icon中心点的偏移量
    content: content, // 自定义点标记覆盖物内容
  });
  marker.value.setMap(map.value); // 设置icon
};

// 生命周期
onMounted(() => {
  initMap();
});

onBeforeUnmount(() => {
  // 清理地图
  if (map.value) {
    map.value.destroy();
  }
});
</script>

<style scoped>
.map-container {
  position: relative;
  width: 100%;
  height: 400px;
}

#map-container {
  width: 100%;
  height: 100%;
}

.map-header {
  position: absolute;
  top: 20px;
  left: 20px;
  z-index: 999;
  width: 400px;
}

.search-input {
  box-shadow: 0 2px 6px rgb(0 0 0 / 30%);
}

.search-results {
  position: absolute;
  top: 80px;
  left: 20px;
  z-index: 999;
  width: 400px;
}

.result-item {
  padding: 10px;
  cursor: pointer;
  border-bottom: 1px solid #eee;
}

.result-item:hover {
  background-color: #f5f5f5;
}

.result-name {
  margin-bottom: 5px;
  font-weight: bold;
}

.result-address {
  font-size: 12px;
  color: #666;
}

.result-distance {
  margin-top: 5px;
  font-size: 12px;
  color: #409eff;
}
</style>
